<template>
    <div class="container">
        <n-card title="用户列表">
            <n-data-table
                :key="(row) => row.id"
                ref="table"
                :bordered="false"
                :columns="columns"
                :data="userList"
                :loading="loadingRef"
                :paginate-single-page="false"
                :pagination="paginationReactive"
                :striped="true"
                remote
                size="large"
                @update:sorter="handleSorterChange"
                @update:filters="handleFiltersChange"
            />
        </n-card>
    </div>
</template>

<script setup>
import { NInput, useMessage } from 'naive-ui'
import { defineComponent, h, nextTick, onMounted, reactive, ref } from 'vue'
import { listClassNumbers, listUsers, listUsersFilterBy, partialUpdateUser } from '../api/user'
import { findKey } from '../utils/mini-lodash'

const message = useMessage()
const loadingRef = ref(true)
const ShowOrEdit = defineComponent({
    props: {
        value: [String, Number],
        onUpdateValue: [Function, Array, Number, String],
    },
    setup (props) {
        const isEdit = ref(false)
        const inputRef = ref(null)
        const inputValue = ref(props.value)

        function handleOnClick () {
            isEdit.value = true
            nextTick(() => {
                inputRef.value.focus()
            })
        }

        function handleChange () {
            props.onUpdateValue(inputValue.value)
            isEdit.value = false
        }

        function handleBlur () {
            isEdit.value = false
        }

        return () =>
            h(
                'div',
                {
                    onClick: handleOnClick,
                },
                isEdit.value
                ? h(NInput, {
                    ref: inputRef,
                    value: findKey(roleList, inputValue.value) !== undefined ? findKey(roleList, inputValue.value)
                        .toString() : inputValue.value.toString(),
                    onUpdateValue: (newValue) => {
                        inputValue.value = newValue
                    },
                    onChange: handleChange,
                    onBlur: handleBlur,
                })
                : props.value.toString(),
            )
    },
})

const paginationReactive = reactive({
    page: 1,
    pageCount: 1,
    pageSize: 5,
    showSizePicker: true,
    itemCount: 0,
    pageSizes: [3, 5, 7],
    prefix ({ itemCount }) {
        return `总数为 ${itemCount} `
    },
    onChange: (page) => {
        paginationReactive.page = page
        fetchUsers(paginationReactive.page)
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        fetchUsers(paginationReactive.page)
    },
})

const column1 = reactive({
    title: '班级',
    key: 'classNumber',
    width: 100,
    filter: true,
    filterOptionValues: [],
    filterOptions: [],
})
const column2 = reactive({
    title: '用户名',
    key: 'username',
    width: 100,
})
const column3 = reactive({
    title: '积分',
    key: 'credit',
    width: 100,
    // sorter: true,
    // sortOrder: false,
    render (row, index) {
        return h(ShowOrEdit, {
            value: row.credit,
            onUpdateValue (newValue) {
                partialUpdateUser(row.id, { credit: newValue }).then(res => {
                    userList.value[index].credit = newValue
                    message.success('修改成功！')
                })
            },
        })
    },
})
const column4 = reactive({
    title: '角色',
    key: 'role',
    width: 100,
    filter: true,
    filterOptionValues: [],
    filterOptions: [
        {
            label: '普通会员',
            value: 1,
        },
        {
            label: '大会员',
            value: 2,
        },
        {
            label: '管理员',
            value: 3,
        },
    ],
    render (row, index) {
        return h(ShowOrEdit, {
            value: row.role,
            onUpdateValue (newValue) {
                if (Number.isInteger(+newValue) && +newValue < 4 && +newValue > 0) {
                    partialUpdateUser(row.id, { role: newValue }).then(res => {
                        userList.value[index].role = roleList[newValue]
                        message.success('修改成功！')
                    })
                } else {
                    message.error('非法输入，请输入正整数！1：普通会员；2：大会员； 3：管理员')
                    userList.value[index].role = row.role
                }
            },
        })
    },
})
const columns = ref([column1, column2, column3, column4])
const userList = ref([])
const roleList = {
    1: '普通会员',
    2: '大会员',
    3: '管理员',
}
const fetchUsers = (currentPage) => {
    loadingRef.value = true
    listUsers(currentPage, paginationReactive.pageSize).then(res => {
        paginationReactive.page = res.data.current
        paginationReactive.pageSize = res.data.size
        paginationReactive.pageCount = res.data.pages
        paginationReactive.itemCount = res.data.total
        userList.value = res.data.records.map((element, index) => {
            return {
                id: element.id,
                index: ++index,
                username: element.username,
                credit: element.credit,
                role: roleList[element.role],
                classNumber: element.classNumber || element.id,
            }
        })
        loadingRef.value = false
    })
}

const fetchClassNumbers = () => {
    listClassNumbers().then(res => {
        res.data.forEach(classNumber => {
            column1.filterOptions.push({ label: classNumber, value: classNumber })
        })
    })
}

const handleSorterChange = (sorter) => {
    if (!sorter || sorter.columnKey === 'column1') {
        if (!loadingRef.value) {
            // loadingRef.value = true
            console.log('排序')
        }
    }
}
const handleFiltersChange = (filters) => {
    if (!loadingRef.value) {
        loadingRef.value = true
        const classValues = filters.classNumber || []
        const roleValues = filters.role || []
        listUsersFilterBy(paginationReactive.page, paginationReactive.pageSize, classValues, roleValues).then(res => {
            paginationReactive.page = res.data.current
            paginationReactive.pageSize = res.data.size
            paginationReactive.pageCount = res.data.pages
            paginationReactive.itemCount = res.data.total
            userList.value = res.data.records.map((element, index) => {
                return {
                    id: element.id,
                    index: ++index,
                    username: element.username,
                    credit: element.credit,
                    role: roleList[element.role],
                    classNumber: element.classNumber || element.id,
                }
            })
            loadingRef.value = false
        })
    }
}

onMounted(() => {
        fetchUsers(paginationReactive.page)
        fetchClassNumbers()
    },
)

</script>

<style scoped>

</style>
